package com.example.app.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;

@Aspect
@Service
public class ExecutionTimeAspect {

    @Pointcut("@annotation(com.example.app.annotation.MonitorTime)")
    public void executionTimePointcut() {}


    @Around("executionTimePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        long startTime = System.currentTimeMillis();
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;
            // 获取方法签名和注解信息
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            System.out.printf(
                    "方法 [%s.%s] 执行时间: %d ms%n",
                    joinPoint.getTarget().getClass().getSimpleName(),
                    method.getName(),
                    duration
            );
        }
    }

}
